<template>
  <div class="app-container">
    <el-button type="success" icon="el-icon-document-add" style="margin-left: 10px" @click="drawerAddUser = true">
      添加用户
    </el-button>
    <template>
      <el-table :data="tableData.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%">

        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="身份证号">
                <span>{{props.row.cardId}}</span>
              </el-form-item>
              <el-form-item label="照片">
                <span>{{props.row.image}}</span>
              </el-form-item>
              <el-form-item label="家庭成员id">
                <span>{{props.row.familyMembersId}}</span>
              </el-form-item>
              <el-form-item label="我的房屋id">
                <span>{{props.row.myHouseId}}</span>
              </el-form-item>
              <el-form-item label="健康档案id">
                <span>{{props.row.healthRecordsId}}</span>
              </el-form-item>
              <el-form-item label="我的积分id">
                <span>{{props.row.myPointsId}}</span>
              </el-form-item>
              <el-form-item label="企业认证id">
                <span>{{props.row.enterpriseCertificationId}}</span>
              </el-form-item>
              <el-form-item label="参与活动id">
                <span>{{props.row.getInvolvedId}}</span>
              </el-form-item>
              <el-form-item label="创建时间">
                <span>{{props.row.createdAt}}</span>
              </el-form-item>
              <el-form-item label="更新时间">
                <span>{{props.row.updatedAt}}</span>
              </el-form-item>
              <el-form-item label="支付密码">
                <el-button @click="togglePasswordVisibility(props.$index)">{{value}}</el-button>
                <span v-if="props.row.showRealPasswords!=1">{{ props.row.payPwd }}</span>
                <span v-else>{{ generateStars(props.row.payPwd.length) }}</span>
              </el-form-item>
              <el-form-item label="角色">
                <span>{{props.row.role}}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="编号" prop="id"></el-table-column>
        <el-table-column label="姓名" prop="name"></el-table-column>
        <el-table-column label="健康状况" prop="healthStatus"></el-table-column>
        <!-- <el-table-column label="图片">
          <template v-slot="scope">
            <img :src="scope.row.image" alt="图片" style="width: 100px; height: 120px;" />
          </template>
        </el-table-column> -->

        <el-table-column label="身高" prop="height"></el-table-column>
        <el-table-column label="体重" prop="weight"></el-table-column>
        <el-table-column label="血型" prop="bloodType"></el-table-column>

        <el-table-column label="状态" prop="state" :formatter="stateFormat"></el-table-column>


        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
            <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
          </template>
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleEdit(scope.$index, scope.row.id)">删除</el-button>
            <el-button size="mini" @click="xiugai(scope.$index)">
              {{scope.row.state=='Y' ? '禁用' : '启用'}}
            </el-button>
            <el-button size="mini" @click="drawerAddUser = true;update(scope.row.userId);">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" @prev-click="prevClick"
        @next-click="nextClick" :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="5"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <div class="app-container">
      <el-drawer title="编辑基本信息" :visible.sync="drawerAddUser" :direction="direction" :before-close="handleClose"
        size="40%">

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini" class="demo-ruleForm">
          <div class="modal-body">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="ruleForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="ruleForm.address"></el-input>
            </el-form-item>
            <el-form-item label="身份证号">
              <el-input v-model="ruleForm.cardId"></el-input>

            </el-form-item>
            <el-form-item label="照片">
              <el-input v-model="ruleForm.image"></el-input>

            </el-form-item>
            <el-form-item label="家庭成员id">
              <el-input v-model="ruleForm.familyMembersId"></el-input>

            </el-form-item>
            <el-form-item label="我的房屋id">
              <el-input v-model="ruleForm.myHouseId"></el-input>

            </el-form-item>
            <el-form-item label="健康档案id">
              <el-input v-model="ruleForm.healthRecordsId"></el-input>

            </el-form-item>
            <el-form-item label="我的积分id">
              <el-input v-model="ruleForm.myPointsId"></el-input>

            </el-form-item>
            <el-form-item label="企业认证id">
              <el-input v-model="ruleForm.enterpriseCertificationId"></el-input>

            </el-form-item>
            <el-form-item label="参与活动id">
              <el-input v-model="ruleForm.getInvolvedId"></el-input>

            </el-form-item>
            <el-form-item label="创建时间">
              <el-input v-model="ruleForm.createdAt"></el-input>

            </el-form-item>
            <el-form-item label="更新时间">
              <el-input v-model="ruleForm.updatedAt"></el-input>

            </el-form-item>
            <el-form-item label="支付密码">
              <el-input v-model="ruleForm.showRealPasswords"></el-input>


            </el-form-item>
            <el-form-item label="角色">
              <el-input v-model="ruleForm.role"></el-input>

            </el-form-item>
          </div>
          <el-form-item>
            <el-button @click="cancelForm; ">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          </el-form-item>
        </el-form>

      </el-drawer>
    </div>
  </div>
</template>

<script>
  import {
    updateByState,
    deleteHealth,
    healthList
  } from '@/api/health';

  export default {
    data() {
      return {
        value: '切换',
        btnname: '',
        flag: 'Y',
        tableData: [],
        currentPage: 1,
        pageNum: 1,
        pageSize: 5,
        total: 0,
        search: '',
        formInline: {
          lxmc: '',
          lxpri: 0,
          xybz: ''
        },
        ruleForm: {

        },
        rules: {
          lxmc: [{
              required: true,
              message: '请输入类型名称',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 5,
              message: '长度在2 到 5 个字符',
              trigger: 'blur'
            }
          ],
          xybz: [{
            required: true,
            message: '请选择是否启用',
            trigger: 'change'
          }],
          lxbz: [{
            required: true,
            message: '请填写类型备注',
            trigger: 'blur'
          }]
        },
        drawerAddUser: false,
        direction: 'rtl',
        loading: false
      };
    },
    computed: {
      generateStars() {
        return (length) => {
          return '*'.repeat(length);
        };
      },
    },
    methods: {

      update(id) {
        this.loading = true;
        updateUserFlagById(id).then(res => {
          console.info('res==>', res);
          this.ruleForm = res
          this.loading = true;
        })
      },
      getList() {
        this.loading = true;
        healthList(this.pageNum, this.pageSize).then(res => {
          console.info('resdsfsad==>', res);
          this.tableData = res.list;
          this.total = res.total;
          this.loading = false;
          this.stateFormat()
        });
      },
      stateFormat(row, column, cellValue) {
        this.btnname = row[column.property] == 'Y' ? '禁用' : '启用';
        return row[column.property] == 'Y' ? '可用' : '不可用';
      },
      dateFormat(row, column) {
        return row[column.property].replace('T', ' ');
      },
      togglePasswordVisibility(index) {

        this.tableData[index].showRealPasswords = !this.tableData[index].showRealPasswords

      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNum = val;
        this.getList();
      },
      prevClick(val) {
        this.pageNum = val;
        this.getList();
      },
      nextClick(val) {
        this.pageNum = val;
        this.getList();
      },
      getListByFlag() {
        this.loading = true;
        userList(this.flag).then(res => {
          this.listLoading = false;
        });
      },
      handleEdit(index, row) {
        console.log(index, row);
        alert(row);
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',

        }).then(() => {
          deleteHealth(row).then(res => {
            this.loading = true;
            if (res) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          }).catch(() => {
            this.loading = false;
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        });
      },
      handleDisable(index, row) {
        console.log(index, row.id);
        if (row.id == 1) {
          this.$message({
            type: 'success',
            message: '当前用户不可禁用'
          });
          return;
        }
        this.$confirm('此操作将更改用户名称为' + row.username + '的应用状态, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          // 执行禁用方法
          updateUserFlagById({
            id: row.id,
            flag: row.flag
          }).then(res => {
            this.listLoading = false;
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.message
              });
              this.getList();
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
          });
        }).catch(() => {
          this.loading = false;
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      handleClose(done) {

        this.$confirm('确定要提交表单吗？').then(_ => {
          this.loading = true;

          done();
          this.ruleForm = [];

          // 动画关闭需要一定的时间

          this.loading = false;

        }).catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.drawerAddUser = false;
        clearTimeout(this.timer);
      },
      submitForm(formName) {


        this.$refs[formName].validate((valid) => {
          console.log(this.ruleForm.value)

          if (valid) {
            this.loading = true;
            add(this.ruleForm).then(res => {
              this.loading = false;
              if (true) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.drawerAddUser = false;
                this.getList();
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                });
              }
            }).catch(() => {
              this.loading = false;
              this.$message({
                type: 'error',
                message: '添加失败!'
              });
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      xiugai(index) {
        console.log("撒大苏打", this.tableData[index])
        updateByState(this.tableData[index]).then(res => {
          this.getList();
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        })

      }
    },

    mounted() {
      this.getList();
    }
  };
</script>

<style scoped>
  .el-pagination {
    float: right;
    margin: 10px;
  }

  .modal-body {
    overflow-y: auto;
    /* 垂直滚动条 */
    max-height: 500px;
    /* 限制最大高度 */
  }

  .cell-text-ellipsis {
    height: 40px;
    /* 设置一个固定高度 */
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
